from flask import Flask, render_template_string, request, redirect, url_for, session
import requests
from functools import wraps
# 智能问答与知识服务平台主页（Flask + 简单HTML模板示例）


app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于session加密
# 论坛数据结构（内存版，实际可用数据库替换）
forum = []  # 每项为 {'question': ..., 'answers': [历史回答, 新回答, ...]}

# 用户示例数据（实际项目应使用数据库）
users = {
    'student': {'password': 'student123', 'role': '学生'},
    'teacher': {'password': 'teacher123', 'role': '教师'},
    'admin': {'password': 'admin123', 'role': '管理员'}
}

# 注册页面模板
register_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <style>
        body { background: #f5f6fa; font-family: "微软雅黑", Arial, sans-serif;}
        .register-box { width: 350px; margin: 100px auto; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px #eee; padding: 40px;}
        h2 { text-align: center; }
        input, select { width: 100%; padding: 10px; margin: 10px 0;}
        button { width: 100%; padding: 10px; background: #3b7ddd; color: #fff; border: none; border-radius: 4px;}
        .error { color: red; text-align: center;}
        .success { color: green; text-align: center;}
    </style>
</head>
<body>
    <div class="register-box">
        <h2>用户注册</h2>
        {% if error %}<div class="error">{{ error }}</div>{% endif %}
        {% if success %}<div class="success">{{ success }}</div>{% endif %}
        <form method="post">
            <input type="text" name="username" placeholder="用户名" required>
            <input type="password" name="password" placeholder="密码" required>
            <input type="text" name="major" placeholder="专业/兴趣" required> <!-- 新增 -->
            <select name="role">
                <option value="学生">学生</option>
                <option value="教师">教师</option>
            </select>
            <button type="submit">注册</button>
        </form>
        <div style="text-align:center;margin-top:10px;">
            <a href="{{ url_for('login') }}">已有账号？去登录</a>
        </div>
    </div>
</body>
</html>
'''

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'username' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

# 注册路由
@app.route('/register', methods=['GET', 'POST'])
def register():
    error = ''
    success = ''
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        role = request.form.get('role')
        major = request.form.get('major')  # 新增
        if role not in ['学生', '教师']:
            error = '只能注册学生或教师账号'
        elif username in users:
            error = '用户名已存在'
        else:
            users[username] = {'password': password, 'role': role, 'major': major}  # 保存专业/兴趣
            return redirect(url_for('login'))
    return render_template_string(register_template, error=error, success=success)

# 修改登录模板，增加注册链接
login_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <style>
        body { background: #f5f6fa; font-family: "微软雅黑", Arial, sans-serif;}
        .login-box { width: 350px; margin: 100px auto; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px #eee; padding: 40px;}
        h2 { text-align: center; }
        input, select { width: 100%; padding: 10px; margin: 10px 0;}
        button { width: 100%; padding: 10px; background: #3b7ddd; color: #fff; border: none; border-radius: 4px;}
        .error { color: red; text-align: center;}
    </style>
</head>
<body>
    <div class="login-box">
        <h2>用户登录</h2>
        {% if error %}<div class="error">{{ error }}</div>{% endif %}
        <form method="post">
            <input type="text" name="username" placeholder="用户名" required>
            <input type="password" name="password" placeholder="密码" required>
            <select name="role">
                <option value="学生">学生</option>
                <option value="教师">教师</option>
                <option value="管理员">管理员</option>
            </select>
            <button type="submit">登录</button>
        </form>
        <div style="text-align:center;margin-top:10px;">
            <a href="{{ url_for('register') }}">没有账号？去注册</a>
        </div>
    </div>
</body>
</html>
'''

# 登录路由
@app.route('/login', methods=['GET', 'POST'])
def login():
    error = ''
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        role = request.form.get('role')
        user = users.get(username)
        if user and user['password'] == password and user['role'] == role:
            session['username'] = username
            session['role'] = role
            session['major'] = user.get('major', '')  # 新增
            return redirect(url_for('home'))
    else:
            error = '用户名、密码或角色错误'
    return render_template_string(login_template, error=error)

# 主页（需登录后访问）
@app.route('/', methods=['GET', 'POST'])
@login_required
def home():
    question = ""
    answer = ""
    forum_answers = []
    if request.method == 'POST':
        question = request.form.get('question', '')
        answer = get_answer(question, mode="简洁")  # 直接用默认模式
    role = session.get('role')
    if role == '学生':
        major = session.get('major', '')
        recommended_questions = generate_excellent_questions(major, 5)
        personalized_resources = generate_personalized_resources(major, 5)
        return render_template_string(
            student_template,
            recommended_questions=recommended_questions,
            sidebar_modules=sidebar_modules,
            question=question,
            answer=answer,
            forum_answers=forum_answers,
            personalized_resources=personalized_resources
        )
    elif role == '教师':
        return render_template_string(teacher_template)
    elif role == '管理员':
        return render_template_string(admin_template)
    else:
        return "未知角色，无法访问", 403

# 登出
@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))

# 学生主页模板
student_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>学生主页</title>
    <style>
        body { font-family: "微软雅黑", Arial, sans-serif; margin: 0; background: #f5f6fa;}
        .container { display: flex; }
        .sidebar {
            width: 220px; background: #2d3a4b; color: #fff; min-height: 100vh; padding: 30px 0;
        }
        .sidebar h2 { text-align: center; font-size: 22px; margin-bottom: 30px;}
        .sidebar ul { list-style: none; padding: 0;}
        .sidebar li { padding: 12px 30px; cursor: pointer;}
        .sidebar li:hover { background: #1a2230;}
        .main { flex: 1; padding: 40px 60px;}
        .search-box { display: flex; margin-bottom: 30px;}
        .search-box input { flex: 1; padding: 12px; font-size: 16px; border: 1px solid #ccc; border-radius: 4px 0 0 4px;}
        .search-box button { padding: 12px 24px; border: none; background: #3b7ddd; color: #fff; font-size: 16px; border-radius: 0 4px 4px 0; cursor: pointer;}
        .answer-modes { margin: 10px 0 20px 0;}
        .answer-modes label { margin-right: 18px;}
        .recommended { background: #fff; padding: 24px; border-radius: 8px; box-shadow: 0 2px 8px #eee;}
        .recommended h3 { margin-top: 0;}
        .recommended ul { padding-left: 20px;}
        .history { margin-top: 30px; background: #fff; padding: 18px; border-radius: 8px;}
        .personal { margin-top: 30px; background: #eaf0fb; padding: 18px; border-radius: 8px;}
        .forum-history { margin-top: 30px; background: #fff; padding: 18px; border-radius: 8px;}
    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <h2>功能导航</h2>
            <ul>
                {% for module in sidebar_modules %}
                <li>{{ module }}</li>
                {% endfor %}
                <li><a href="{{ url_for('forum_page') }}" style="color:#fff;">论坛</a></li>
            </ul>
        </div>
        <div class="main">
            <h1>学生智能问答与知识服务平台</h1>
            <div style="text-align:right;">
                <a href="{{ url_for('logout') }}" style="color:#3b7ddd;">退出登录</a>
            </div>
            <form class="search-box" method="post">
                <input type="text" name="question" placeholder="请输入您的学术或学习问题..." value="{{ question|default('') }}">
                <button type="submit">提问</button>
            </form>
            {% if forum_answers %}
            <div class="forum-history">
                <strong>论坛历史回答：</strong>
                <ul>
                    {% for ans in forum_answers %}
                    <li>{{ ans }}</li>
                    {% endfor %}
                </ul>
            </div>
            {% endif %}
            {% if answer %}
            <div class="history">
                <strong>您的问题：</strong> {{ question }}<br>
                <strong>答复（{{ mode }}）：</strong> {{ answer }}
            </div>
            {% endif %}
            <div class="recommended">
                <h3>推荐问题与主题导航</h3>
                <ul>
                    {% for q in recommended_questions %}
                    <li>{{ q }}</li>
                    {% endfor %}
                </ul>
            </div>
            <div class="personalized">
                <h3>个性化学习资源推荐</h3>
                <ul>
                    {% for res in personalized_resources %}
                    <li>{{ res }}</li>
                    {% endfor %}
                </ul>
            </div>
        </div>
    </div>
</body>
</html>
'''

# 教师主页模板
teacher_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>教师主页</title>
</head>
<body>
    <h1>欢迎，教师 {{ session['username'] }}</h1>
    <a href="{{ url_for('logout') }}">退出登录</a>
    <p>这里是教师专属功能区。</p>
</body>
</html>
'''

# 管理员主页模板
admin_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>管理员主页</title>
</head>
<body>
    <h1>欢迎，管理员 {{ session['username'] }}</h1>
    <a href="{{ url_for('logout') }}">退出登录</a>
    <p>这里是管理员专属功能区。</p>
</body>
</html>
'''

# 新增论坛页面模板
forum_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>学生论坛</title>
    <style>
        body { font-family: "微软雅黑", Arial, sans-serif; background: #f5f6fa; }
        .forum-box { width: 800px; margin: 40px auto; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px #eee; padding: 40px;}
        h2 { text-align: center; }
        .q { font-weight: bold; margin-top: 20px;}
        .a { margin-left: 20px; color: #333;}
        .divider { border-bottom: 1px solid #eee; margin: 18px 0;}
    </style>
</head>
<body>
    <div class="forum-box">
        <h2>学生论坛</h2>
        {% for item in forum %}
            <div class="q">Q: {{ item.question }}</div>
            {% for ans in item.answers %}
                <div class="a">A: {{ ans }}</div>
            {% endfor %}
            <div class="divider"></div>
        {% endfor %}
        <div style="text-align:center;">
            <a href="{{ url_for('home') }}">返回主页</a>
        </div>
    </div>
</body>
</html>
'''

# 论坛页面路由
@app.route('/forum')
def forum_page():
    return render_template_string(forum_template, forum=forum)

# 侧边功能栏模块
sidebar_modules = [
    "学术搜索",
    "期刊文献",
    "学者信息",
    "知识库管理",
    "实验与计算工具"
]

# 简单主页模板
template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>智能问答与知识服务平台</title>
    <style>
        body { font-family: "微软雅黑", Arial, sans-serif; margin: 0; background: #f5f6fa;}
        .container { display: flex; }
        .sidebar {
            width: 220px; background: #2d3a4b; color: #fff; min-height: 100vh; padding: 30px 0;
        }
        .sidebar h2 { text-align: center; font-size: 22px; margin-bottom: 30px;}
        .sidebar ul { list-style: none; padding: 0;}
        .sidebar li { padding: 12px 30px; cursor: pointer;}
        .sidebar li:hover { background: #1a2230;}
        .main { flex: 1; padding: 40px 60px;}
        .search-box { display: flex; margin-bottom: 30px;}
        .search-box input { flex: 1; padding: 12px; font-size: 16px; border: 1px solid #ccc; border-radius: 4px 0 0 4px;}
        .search-box button { padding: 12px 24px; border: none; background: #3b7ddd; color: #fff; font-size: 16px; border-radius: 0 4px 4px 0; cursor: pointer;}
        .answer-modes { margin: 10px 0 20px 0;}
        .answer-modes label { margin-right: 18px;}
        .recommended { background: #fff; padding: 24px; border-radius: 8px; box-shadow: 0 2px 8px #eee;}
        .recommended h3 { margin-top: 0;}
        .recommended ul { padding-left: 20px;}
        .history { margin-top: 30px; background: #fff; padding: 18px; border-radius: 8px;}
        .personal { margin-top: 30px; background: #eaf0fb; padding: 18px; border-radius: 8px;}
    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <h2>功能导航</h2>
            <ul>
                {% for module in sidebar_modules %}
                <li>{{ module }}</li>
                {% endfor %}
            </ul>
        </div>
        <div class="main">
    <h1>智能问答与知识服务平台</h1>
    <div style="text-align:right;">
        <a href="{{ url_for('logout') }}" style="color:#3b7ddd;">退出登录</a>
    </div>
    <form class="search-box" method="post">
        <input type="text" name="question" placeholder="请输入您的学术或学习问题..." value="{{ question|default('') }}">
        <button type="submit">提问</button>
    </form>
            <div class="answer-modes">
                <label><input type="radio" name="mode" value="简洁" {% if mode=='简洁' %}checked{% endif %}> 简洁</label>
                <label><input type="radio" name="mode" value="详细" {% if mode=='详细' %}checked{% endif %}> 详细</label>
                <label><input type="radio" name="mode" value="带引用" {% if mode=='带引用' %}checked{% endif %}> 带引用</label>
            </div>
            {% if answer %}
            <div class="history">
                <strong>您的问题：</strong> {{ question }}<br>
                <strong>答复（{{ mode }}）：</strong> {{ answer }}
            </div>
            {% endif %}
            <div class="recommended">
                <h3>推荐问题与主题导航</h3>
                <ul>
                    {% for q in recommended_questions %}
                    <li>{{ q }}</li>
                    {% endfor %}
                </ul>
            </div>
            <div class="personal">
                <strong>个性化与交互：</strong>
                <ul>
                    <li>历史对话追溯</li>
                    <li>订阅最新学术进展</li>
                    <li>跨端使用支持</li>
                </ul>
            </div>
        </div>
    </div>
</body>
</html>
'''

def get_answer(question, mode):
    if not question:
        return ""
    api_key = "sk-604669f6c0554500b96549d52fccaaad"  # 建议生产环境不要明文写密钥
    url = "https://api.deepseek.com/v1/chat/completions"  # DeepSeek API 地址
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    prompt = (
        f"请用{mode}模式回答以下问题，并且答案必须包含：\n"
        f"1. 解题步骤\n"
        f"2. 核心知识点\n"
        f"3. 参考资料\n"
        f"问题：{question}"
    )
    data = {
        "model": "deepseek-chat",  # DeepSeek 的模型名，具体以官方文档为准
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 512
    }
    try:
        resp = requests.post(url, headers=headers, json=data, timeout=20)
        resp.raise_for_status()
        result = resp.json()
        return result["choices"][0]["message"]["content"].strip()
    except Exception as e:
        return f"AI服务调用失败：{e}"
    
def get_questions_from_ai(prompt):
    api_key = "sk-604669f6c0554500b96549d52fccaaad"
    url = "https://api.deepseek.com/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    data = {
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 512
    }
    try:
        resp = requests.post(url, headers=headers, json=data, timeout=20)
        resp.raise_for_status()
        result = resp.json()
        return result["choices"][0]["message"]["content"].strip()
    except Exception as e:
        return f"AI服务调用失败：{e}"

def generate_personalized_resources(major, n=5):
    prompt = (
        f"请为专业或兴趣为“{major}”的大学生推荐{n}个优质学习资源，每个资源只给出名称和一个词语简要说明用途，用“资源名：用途”格式输出，每个资源独立成行，不要详细描述。"
    )
    ai_result = get_questions_from_ai(prompt)
    resources = [line.strip(" 0123456789.、") for line in ai_result.split('\n') if line.strip()]
    return resources

def generate_excellent_questions(major, n=10):
    prompt = (
        f"请你以专业或兴趣为“{major}”的大学生的视角，列举{n}个优质学术问题，内容涵盖学习方法、科研、论文写作、考试准备等，每个问题独立成行，只输出问题本身，不要输出任何解答。"
    )
    ai_result = get_questions_from_ai(prompt)
    questions = [line.strip(" 0123456789.、") for line in ai_result.split('\n') if line.strip()]
    return questions

if __name__ == '__main__':
    app.run(debug=True)